package com.tange.ai.iot.client.gnssa.binding

import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.os.Vibrator
import android.view.View
import android.view.Window
import android.view.WindowManager
import android.widget.RelativeLayout
import androidx.appcompat.app.AppCompatActivity
import androidx.core.util.Consumer
import com.tange.ai.iot.client.gnssa.databinding.ActivityInternalQrcodeScanBinding
import com.tange.base.toolkit.*
import com.tange.core.access.token.Authentication
import com.tange.core.access.token.Token
import com.tange.core.backend.service.http.HttpConfigurations
import com.tange.core.data.structure.Resp
import com.tg.appcommon.android.TGLog

class BindingQrcodeScanActivity: AppCompatActivity() {

    private companion object {
        private const val TAG = "BindingQrcodeScanActivity"
        private const val VIBRATE_DURATION_MILLISECONDS = 80L
        private const val RECOGNITION_INTERVAL = 1000
    }

    private lateinit var binding: ActivityInternalQrcodeScanBinding

    private var recentlyRecognizedMoment = 0L

    override fun onCreate(savedInstanceState: Bundle?) {
        requestWindowFeature(Window.FEATURE_NO_TITLE)
        StatusBarUtil.setLightStatusBar(this, true)
        StatusNavUtils.setTranslucentStatus(this)
        super.onCreate(savedInstanceState)

        binding = ActivityInternalQrcodeScanBinding.inflate(layoutInflater).apply {
            setContentView(root)
            supportActionBar?.hide()
            top.left.onClicked { finish() }
            tips.text = "扫描设备二维码"
            top.title.text = "扫一扫"
            top.title.setTextColor(Color.WHITE)
        }

        (binding.top.layoutParams as RelativeLayout.LayoutParams).apply {
            topMargin = DisplayUtils.statusBarHeight(this@BindingQrcodeScanActivity)
            binding.top.layoutParams = this
        }

        window.apply {
            var uiFlags = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
            uiFlags = uiFlags or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
            clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
            addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
            statusBarColor = Color.TRANSPARENT
            decorView.systemUiVisibility = uiFlags
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
            }
        }

        binding.qrCodeScan.setOnQrCodeScanListener { result -> onQrcodeRecognized(result) }

    }

    private fun configure(packageName: String, appId: String, accessToken: String, consumer: Consumer<Resp<Token?>>) {
        HttpConfigurations.getInstance().appId = appId
        HttpConfigurations.getInstance().packageName = packageName
        Authentication.configure(accessToken, consumer)
    }

    private fun isValidDeviceId(input: String): Boolean {
        val regex = Regex("^[A-Z0-9]{12}$")
        return regex.matches(input)
    }

    private fun onQrcodeRecognized(result: String?) {
        TGLog.i(TAG, "[onQrcodeRecognized] $result")
        if (now() - recentlyRecognizedMoment <= RECOGNITION_INTERVAL) return
        recentlyRecognizedMoment = now()
        (getSystemService(Context.VIBRATOR_SERVICE) as Vibrator).vibrate(VIBRATE_DURATION_MILLISECONDS)
        result?.let {

            try {
                if (isValidDeviceId(it)) {
                    Intent().apply {
                        putExtra("device_id", it)
                    }.also {
                        setResult(RESULT_OK, it)
                        finish()
                    }
                }
            } catch (e: Throwable) {
                Tips.show("不合法的二维码！")
                finish()
            }
            finish()
        }
    }

    override fun onResume() {
        super.onResume()
        binding.qrCodeScan.onStart()
    }

    override fun onPause() {
        super.onPause()
        binding.qrCodeScan.onStop()
    }

    override fun onDestroy() {
        super.onDestroy()
        binding.qrCodeScan.onDestroy()
    }
}